package com.unnet.yjs;

import com.unnet.yjs.util.ConstantsUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * Email: love1208tt@foxmail.com
 * Copyright (c)  2019. missbe
 * @author lyg   19-5-30 下午8:35
 *
 *
 **/
@Configuration
@EnableSwagger2
public class Swagger2Config {

    /**是否开启swagger，正式环境一般是需要关闭的，可根据springboot的多环境配置进行设置*/
    @Value(value = "${swagger.enabled}")
    Boolean swaggerEnabled;
    @Value(value = "${swagger.version}")
    String version;

    @Bean
    public Docket createRestApi() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("api_key")
                .description("token[请求添加token字段,登录成功生成].")
                .modelRef(new ModelRef("string")).parameterType("header")
                //header中的ticket参数非必填，传空也可以
                .required(false)
                .defaultValue(ConstantsUtil.JWT_CLAIM)
                .build();
        //根据每个方法名也知道当前方法在设置什么参数
        pars.add(tokenPar.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(swaggerEnabled)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.unnet.yjs.controller"))
                .paths(PathSelectors.any())
                .build()
                //主要关注点--统一填写一次token
                .securitySchemes(security())
                .globalOperationParameters(pars);
    }

    private List<ApiKey> security() {
        return newArrayList(
                new ApiKey("token", "token", "header")
        );
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("File Upload-Swagger2 APIs")
                .termsOfServiceUrl("https://blog.csdn.net/lovequanquqn?viewmode=list")
                .contact(new Contact("unnet","https://blog.csdn.net/lovequanquqn?viewmode=list","love1208tt@foxmail.com"))
                .version(version)
                .build();
    }
}
